package document;

import java.io.IOException;
import java.io.RandomAccessFile;

 

public class Record {
	
	public static final int NAME_SIZE=40;
	public static final int RECORD_SIZE=2*NAME_SIZE+2+4+4;
		
	private String name ;//40个字节
	private char attribute; //文件的属性 ，1个字节（可执行文件扩展名为e，目录没有扩展名）
    private int dnum; //磁盘盘块号
	 
	private int length; //文件长度（目录长度固定为0，不需要关心。文件长度为块长）
	
	public Record(){
		
	}
	
	public Record(String name,char attribute, int dnum , int length){
	this.name=name;
	this.attribute=attribute;
	this.dnum=dnum;
	 
	this.length=length;
	}
    
    public String getName() {
		return  name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public char getAttribute() {
		return attribute;
	}
	public void setAttribute(char attribute) {
		this.attribute = attribute;
	}
	public int getDnum() {
		return dnum;
	}
	public void setDnum(int dnum) {
		this.dnum = dnum;
	}
	 
	public int getLength() {
		return length;
	}
	public void setLength(int length) {
		this.length = length;
	}
	 
	public String toString(){
		return getClass().getName()
				+"[name="+name
				+",attribute"+attribute
				+",dnum"+dnum
			 
				+",length"+length
				+"]";
		 
	}
	
	public void writeData(RandomAccessFile out) throws IOException{
		DataIO.writeFixedString(name,NAME_SIZE,out);
		out.writeChar(attribute);
		out.writeInt(dnum);
		 
		out.writeInt(length);
		
	}
	
	public void readData(RandomAccessFile in)throws IOException{
		this.name=DataIO.readFixedString(NAME_SIZE,in);
		this.attribute=in.readChar();
		this.dnum=in.readInt();
		 
		this.length=in.readInt();
		
	}
      
}

class DataIO{
	
	public static String readFixedString(int size,RandomAccessFile in)throws IOException{
		StringBuilder b=new StringBuilder(size);
		int i=0;
		boolean more=true;
		while(more&&i<size){
			char ch=in.readChar();
			i++;
			if(ch==0)more=false;
			else b.append(ch);			
		}
		
		in.skipBytes(2*(size-i));
		return b.toString();
		
	}
	
	public static void writeFixedString(String s,int size,RandomAccessFile out)throws IOException{
		for(int i=0;i<size;i++){
			char ch=0;
			if(i<s.length()) ch=s.charAt(i);
			out.writeChar(ch);
		}
	}
}
